<template>
  <form class="h-full w-[calc(100vw-15px)] mx-1 flex items-center justify-center text-center" @submit.prevent="active">
    <div id="app" class="w-full pt-8 pb-2 bg-white rounded-lg shadow-md">
      <div class="font-bold select-none">当前时间: {{newTime}} </div>
        <div @click="getActoken">
          <vue-qrcode 
            class="border-4 border-green-900 rounded-lg w-64 h-64 my-3 mx-auto select-none"
            :width="250"
            :value="qrCode"
            :size="qrCodeSize"
            :color="{ dark: '#000000ff', light: '#ffffffff' }"  
            :type="'image/png'">
          </vue-qrcode>
        </div>
        <inputComponent @confirm="updateCode"></inputComponent>
        <button class="w-1/4 h-10 bg-slate-50 font-bold" type="submit">激活</button>
        <div class="text-sm text-gray-500 mt-10 select-none">Copyright © 2013 - 2024 OddString.</div>
    </div>
  </form>

</template>

<script setup lang="ts">
import { onMounted, ref } from "vue";
import { WebviewWindow } from "@tauri-apps/api/window";
import { invoke } from '@tauri-apps/api/tauri'
import { ElMessage } from 'element-plus'

const keyCode = ref("");
const qrCode = ref('');
const qrCodeSize = ref(200);
const newTime = ref(new Date().toLocaleString());

onMounted(async () => {
  if (await verify_to_work() == false){
      setInterval(() => {
      newTime.value = new Date().toLocaleString();
    }, 1000);
    getActoken();
  };
});

async function verify_to_work () {
  let result = invoke("verify_lic_cmd");
  if(await result){
    const loginWindow = WebviewWindow.getByLabel("login");
    loginWindow?.hide();
    // 创建新窗口
    const webview = new WebviewWindow("work", {
      url: "#/work",
      center: true,
      minWidth: 1000,
      minHeight: 600,
      height:700,
      width: 1000,
      decorations: true,
      title: "RCIOS",
      // alwaysOnTop:true,
    });
      webview.once("tauri://created", function () {
      loginWindow?.close();
    });
  }else{
  }
  return result;
}

async function getActoken () {
  let result:string = await invoke("gen_actoken_cmd");
  if(result){
    qrCode.value = result.trim();
    console.log("getActoken:",result);
  }
}

async function updateCode (code: string) {
  keyCode.value = code;
}

async function active () {
  if(keyCode.value.length != 4){
    console.log("请输入正确的注册码");
    return;
  }

  const content = keyCode.value  + qrCode.value;//active_license_cmd
  let result:boolean = await invoke("active_license_cmd",{content:content});
  if(result){
    verify_to_work();
  }else{
    ElMessage({ message: '注册失败', type: 'warning'})
    getActoken();
  }
  
}

</script>



<script lang="ts">
import inputComponent from "../components/RegInput.vue";
export default {
  name: "Active",
  components: {
    inputComponent
  },
}
</script>

<style scoped>

</style>

<!-- TODO: 弹出窗提示状态 -->